import * as Notifications from "expo-notifications";
import SystemUtils from "@/utils/system-utils";
import {NOTIFICATION_SERVICE_TYPE} from "@/config/notification";
import * as SecureStore from "expo-secure-store";

// Expo Push token 存储的键
const expoPushStoreKey = "expo_push_token";

// JPush token 存储的键
const jPushStoreKey = "jpush_token";
/**
 * 请求通知权限
 */
async function requestNotificationPermissions(): Promise<boolean> {
    const {status: existingStatus} = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;

    if (existingStatus !== "granted") {
        const {status} = await Notifications.requestPermissionsAsync();
        finalStatus = status;
    }

    if (finalStatus !== "granted") {
        SystemUtils.showSystemAlert("请在系统设置中开启通知权限");
        return false;
    }

    return true;
}

/**
 * 设置当前用户ID
 * @param token 推送令牌
 */
function setToken(token: string): void {
    switch (NOTIFICATION_SERVICE_TYPE) {
        case "expo":
            // Expo 推送令牌存储
            SecureStore.setItemAsync(expoPushStoreKey, token);
            break;
        case "jpush":
            // JPush 推送令牌存储
            SecureStore.setItemAsync(jPushStoreKey, token);
            break;
        default:
            throw new Error("Unsupported notification service type");
    }
}

/**
 * 获取当前推送令牌
 */
function getToken(): string | null {
    switch (NOTIFICATION_SERVICE_TYPE) {
        case "expo":
            // 获取 Expo 推送令牌
            return SecureStore.getItem(expoPushStoreKey);
        case "jpush":
            // 获取 JPush 推送令牌
            return SecureStore.getItem(jPushStoreKey);
        default:
            throw new Error("Unsupported notification service type");
            }
}

/**
 * 清除当前推送令牌
 */
async function clearToken(): Promise<void> {
    await SecureStore.deleteItemAsync(expoPushStoreKey);
    await SecureStore.deleteItemAsync(jPushStoreKey);
}


export default {
    requestNotificationPermissions,
    setToken,
    getToken,
    clearToken
}